/**
 * 任务状态管理
 */

import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import type { Task, TaskStatus } from '../types'
import { apiService } from '../services/api'

export const useTaskStore = defineStore('task', () => {
  // 状态
  const tasks = ref<Task[]>([])
  const currentTask = ref<Task | null>(null)
  const loading = ref(false)
  const error = ref<string | null>(null)
  const pagination = ref({
    page: 1,
    limit: 10,
    total: 0
  })

  // 计算属性
  const activeTasks = computed(() => 
    tasks.value.filter(task => 
      task.status === 'pending' || task.status === 'processing'
    )
  )

  const completedTasks = computed(() =>
    tasks.value.filter(task => task.status === 'completed')
  )

  const failedTasks = computed(() =>
    tasks.value.filter(task => task.status === 'failed')
  )

  const totalTasks = computed(() => tasks.value.length)

  // 操作方法
  const addTask = (task: Task) => {
    const existingIndex = tasks.value.findIndex(t => t.id === task.id)
    if (existingIndex >= 0) {
      tasks.value[existingIndex] = task
    } else {
      tasks.value.unshift(task)
    }
  }

  const updateTask = (taskId: string, updates: Partial<Task>) => {
    const index = tasks.value.findIndex(t => t.id === taskId)
    if (index >= 0) {
      tasks.value[index] = { ...tasks.value[index], ...updates }
    }
  }

  const updateTaskProgress = (taskId: string, progress: {
    progress: number
    status?: TaskStatus
    currentStep?: string
  }) => {
    updateTask(taskId, progress)
  }

  const removeTask = (taskId: string) => {
    const index = tasks.value.findIndex(t => t.id === taskId)
    if (index >= 0) {
      tasks.value.splice(index, 1)
    }
  }

  const getTaskById = (taskId: string): Task | undefined => {
    return tasks.value.find(t => t.id === taskId)
  }

  const setCurrentTask = (task: Task | null) => {
    currentTask.value = task
  }

  const setLoading = (isLoading: boolean) => {
    loading.value = isLoading
  }

  const setError = (errorMessage: string | null) => {
    error.value = errorMessage
  }

  // 异步操作
  const fetchTasks = async (params?: {
    status?: TaskStatus
    page?: number
    limit?: number
    search?: string
  }) => {
    try {
      setLoading(true)
      setError(null)
      
      const response = await apiService.getTasks(params)
      
      tasks.value = response.tasks
      pagination.value = {
        page: response.page,
        limit: response.limit,
        total: response.total
      }
      
      return response
    } catch (err) {
      const errorMessage = err instanceof Error ? err.message : '获取任务列表失败'
      setError(errorMessage)
      throw err
    } finally {
      setLoading(false)
    }
  }

  const createTask = async (file: File, options: {
    outputFormat: string
    quality?: string
    customOptions?: Record<string, any>
  }) => {
    try {
      setLoading(true)
      setError(null)
      
      const task = await apiService.createTask(file, options)
      addTask(task)
      
      return task
    } catch (err) {
      const errorMessage = err instanceof Error ? err.message : '创建任务失败'
      setError(errorMessage)
      throw err
    } finally {
      setLoading(false)
    }
  }

  const cancelTask = async (taskId: string) => {
    try {
      await apiService.cancelTask(taskId)
      updateTask(taskId, { status: 'cancelled' })
    } catch (err) {
      const errorMessage = err instanceof Error ? err.message : '取消任务失败'
      setError(errorMessage)
      throw err
    }
  }

  const retryTask = async (taskId: string) => {
    try {
      const task = await apiService.retryTask(taskId)
      updateTask(taskId, task)
      return task
    } catch (err) {
      const errorMessage = err instanceof Error ? err.message : '重试任务失败'
      setError(errorMessage)
      throw err
    }
  }

  const deleteTask = async (taskId: string) => {
    try {
      await apiService.deleteTask(taskId)
      removeTask(taskId)
    } catch (err) {
      const errorMessage = err instanceof Error ? err.message : '删除任务失败'
      setError(errorMessage)
      throw err
    }
  }

  const downloadTask = async (taskId: string) => {
    try {
      const blob = await apiService.downloadTask(taskId)
      const task = getTaskById(taskId)
      
      if (task) {
        const url = URL.createObjectURL(blob)
        const link = document.createElement('a')
        link.href = url
        link.download = task.filename.replace(/\.[^/.]+$/, `.${task.outputFormat}`)
        link.click()
        URL.revokeObjectURL(url)
      }
    } catch (err) {
      const errorMessage = err instanceof Error ? err.message : '下载任务失败'
      setError(errorMessage)
      throw err
    }
  }

  const batchCancelTasks = async (taskIds: string[]) => {
    try {
      await apiService.batchCancelTasks(taskIds)
      taskIds.forEach(id => {
        updateTask(id, { status: 'cancelled' })
      })
    } catch (err) {
      const errorMessage = err instanceof Error ? err.message : '批量取消任务失败'
      setError(errorMessage)
      throw err
    }
  }

  const batchDeleteTasks = async (taskIds: string[]) => {
    try {
      await apiService.batchDeleteTasks(taskIds)
      taskIds.forEach(id => {
        removeTask(id)
      })
    } catch (err) {
      const errorMessage = err instanceof Error ? err.message : '批量删除任务失败'
      setError(errorMessage)
      throw err
    }
  }

  const fetchTaskStatus = async (taskId: string) => {
    try {
      setLoading(true)
      setError(null)
      
      const task = await apiService.getTask(taskId)
      addTask(task)
      return task
    } catch (err) {
      const errorMessage = err instanceof Error ? err.message : '获取任务状态失败'
      setError(errorMessage)
      throw err
    } finally {
      setLoading(false)
    }
  }

  const fetchHistory = async (page: number = 1, perPage: number = 10) => {
    try {
      setLoading(true)
      setError(null)
      
      const response = await apiService.getTasks({
        page,
        limit: perPage
      })
      
      tasks.value = response.tasks
      pagination.value = {
        page: response.page,
        limit: response.limit,
        total: response.total
      }
      
      return response
    } catch (err) {
      const errorMessage = err instanceof Error ? err.message : '获取历史记录失败'
      setError(errorMessage)
      throw err
    } finally {
      setLoading(false)
    }
  }

  const clearError = () => {
    setError(null)
  }

  const clearTasks = () => {
    tasks.value = []
  }

  return {
    // 状态
    tasks,
    currentTask,
    loading,
    error,
    pagination,
    
    // 计算属性
    activeTasks,
    completedTasks,
    failedTasks,
    totalTasks,
    
    // 操作方法
    addTask,
    updateTask,
    updateTaskProgress,
    removeTask,
    getTaskById,
    setCurrentTask,
    setLoading,
    setError,
    clearError,
    clearTasks,
    
    // 异步操作
    fetchTasks,
    createTask,
    cancelTask,
    retryTask,
    deleteTask,
    downloadTask,
    batchCancelTasks,
    batchDeleteTasks,
    fetchTaskStatus,
    fetchHistory,
  }
})